document.addEventListener('DOMContentLoaded', () => {
  const mongoConfigBtn = document.getElementById('mongoConfigBtn');
  // 获取extractAmazonProductDetailBtn
  const extractAmazonProductDetailBtn = document.getElementById('extractAmazonProductDetailBtn');
  // 获取extractAllAmazonProductsFromListBtn
  const extractAllAmazonProductsFromListPagesBtn = document.getElementById('extractAllAmazonProductsFromListPagesBtn');
  const openAllSearchResultsBtn = document.getElementById('openAllSearchResultsBtn');
  const getAllReviewColorSizesBtn = document.getElementById('getAllReviewColorSizesBtn');

  mongoConfigBtn.addEventListener('click', showMongoConfigDialog);
  extractAmazonProductDetailBtn.addEventListener('click', extractAmazonProductDetail);
  extractAllAmazonProductsFromListPagesBtn.addEventListener('click', extractAllAmazonProductsFromListPages);
  openAllSearchResultsBtn.addEventListener('click', openAllSearchResults);
  getAllReviewColorSizesBtn.addEventListener('click', getAllReviewColorSizes);

});

async function loadMongoConfig() {
  return new Promise((resolve) => {
    chrome.storage.local.get(['mongoConfig'], (result) => {
      resolve(result.mongoConfig || null);
    });
  });
}

async function showMongoConfigDialog() {
  const config = await loadMongoConfig();
  const modalHTML = `
    <div id="mongoConfigModal" class="modal">
      <div class="modal-content">
        <h3>MongoDB Configuration</h3>
        <form id="mongoConfigForm">
          <label for="mongoIp">MongoDB IP:</label>
          <input type="text" id="mongoIp" required value="${config?.ip || ''}">
          
          <label for="mongoPort">MongoDB PORT:</label>
          <input type="text" id="mongoPort" required value="${config?.port || ''}">
          
          <label for="mongoUser">MongoDB Username:</label>
          <input type="text" id="mongoUser" value="${config?.user || ''}">
          
          <label for="mongoPass">MongoDB Password:</label>
          <input type="password" id="mongoPass" value="${config?.pass || ''}">
          
          <label for="mongoDb">MongoDB Database:</label>
          <input type="text" id="mongoDb" required value="${config?.db || ''}">
          
          <div class="modal-actions">
            <button type="button" id="cancelBtn">Cancel</button>
            <button type="submit">Save</button>
          </div>
        </form>
      </div>
    </div>
  `;
  
  document.body.insertAdjacentHTML('beforeend', modalHTML);
  const modal = document.getElementById('mongoConfigModal');
  const form = document.getElementById('mongoConfigForm');
  const cancelBtn = document.getElementById('cancelBtn');
  
  modal.style.display = 'block';
  
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const config = {
      ip: document.getElementById('mongoIp').value,
      port: document.getElementById('mongoPort').value,
      user: document.getElementById('mongoUser').value,
      pass: document.getElementById('mongoPass').value,
      db: document.getElementById('mongoDb').value
    };
    chrome.storage.local.set({ mongoConfig: config }, () => {
      hideModal(modal);
    });
  });
  
  cancelBtn.addEventListener('click', () => hideModal(modal));
}

function hideModal(modal) {
  modal.style.display = 'none';
  modal.remove();
}

async function getMongoUrl() {
  const config = await loadMongoConfig();
  if (!config) {
    throw new Error('MongoDB configuration not found');
  }

  const { ip, port, user, pass, db } = config;
  const auth = user && pass ? `${user}:${pass}@` : '';
  const mongoUrl = `mongodb://${auth}${ip}:${port}/${db}`;
  console.log('MongoDB URL:', mongoUrl);
  return mongoUrl;
}

async function saveToMongoDB(collection, data) {
  try {
    const mongoUrl = await getMongoUrl();

    const response = await chrome.runtime.sendMessage({
      action: 'saveToMongoDB',
      url: mongoUrl,
      collection,
      data: data
    });

    if (!response.success) {
      throw new Error(response.error || 'Failed to save to MongoDB');
    }

    return response;
  } catch (error) {
    console.error('Error saving to MongoDB:', error);
    throw error;
  }
}

async function extractAmazonProductDetail() {
  try {
    const mongoUrl = await getMongoUrl();
    const result = await chrome.runtime.sendMessage({
      action: 'extractAndSaveAmazonProductDetail',
      url: mongoUrl,
      autoScroll: true
    });

    if (!result.success) {
      throw new Error(result.error);
    }

    alert(`extractAmazonProductDetail successfully: ${JSON.stringify(result.result)}`);
  } catch (error) {
    console.error('Error:', error);
    alert(`extractAmazonProductDetail Error: ${error.message}. Please check if mongodb proxy is started.`);
  }
}

async function openAllSearchResults() {
  try {
    const result = await chrome.runtime.sendMessage({
      action: 'openAllSearchResults'
    });

    if (!result.success) {
      throw new Error(result.error);
    }

    alert('Opening all search results in new tabs');
  } catch (error) {
    console.error('Error:', error);
    alert(`openAllSearchResults Error: ${error.message}`);
  }
}

async function getAllReviewColorSizes() {
  try {
    const result = await chrome.runtime.sendMessage({
      action: 'getAllReviewColorSizes'
    });

    if (!result || !result.success) {
      throw new Error(result.error);
    }

    alert('getAllReviewColorSizes done!');
  }
  catch (error) {
    console.error('Error:', error);
    alert(`getAllReviewColorSizes Error: ${error.message}`);
  }
}

async function extractAllAmazonProductsFromListPages() {
  try {
    const numberOfPages = parseInt(prompt('Enter the number of pages to extract:', '0'), 10);
    const mongoUrl = await getMongoUrl();
    const result = await chrome.runtime.sendMessage({
      action: 'extractAllAmazonProductsFromListPages',
      url: mongoUrl,
      autoScroll: true,
      numberOfPages
    });

    if (!result.success) {
      throw new Error(result.error);
    }

    alert('extractAllAmazonProductsFromListPages done!');
  } catch (error) {
    console.error('Error:', error);
    alert(`extractAllAmazonProductsFromListPages Error: ${error.message}`);
  }
}
